import store from "../../../../../utils/store"
import request from "../../../../../plugins/request"
import { valIsNull } from "../../../../../utils/utils"

Component({
	data: {
		agreementDetail: "", // 协议内容
		agreementMinTime: 0, // 协议最小阅读时间
		hasReadAgreementDetail: false, // 是否已经阅读协议详情
		agreement: false, // 是否同意协议
	},
	ready() {
		this.setData({
			agreement: store.agreement.get(),
			hasReadAgreementDetail: store.hasReadAgreementDetail.get(),
		})
	},
	methods: {
		//获取用户协议（供父组件调用）
		getAgreementDetail(schoolId) {
			wx.showLoading({
				title: "加载中",
			})
			request({
				url: "api/wx/xshy/get-policy",
				method: "post",
				noAuth: true,
				data: {
					payloads: {
						schoolId: schoolId,
					},
				},
			})
				.then((data) => {
					wx.hideLoading()
					this.setData({
						agreementDetail: data.policy,
						agreementMinTime: !valIsNull(data.policyMinTime)
							? data.policyMinTime
							: 0,
					})
				})
				.catch((err) => {
					wx.hideLoading()
					console.log(err)
					wx.showToast({
						title: err,
						icon: "none",
					})
				})
		},
		//打开阅读用户协议
		handleOpenAgreementDetail() {
			//开启倒计时
			const intervalId = setInterval(() => {
				const agreementMinTime = this.data.agreementMinTime
				if (agreementMinTime <= 0) {
					clearInterval(intervalId)
					return
				}
				this.setData({
					agreementMinTime: agreementMinTime - 1,
				})
			}, 1000)
			//打开协议详情弹框
			const popup = this.selectComponent("#bottom-popup")
			popup.show()
		},
		// 用户协议弹框关闭
		closeAgreementPopup(e) {
			const trigger = e.currentTarget.dataset.trigger
			if (trigger === "agree") {
				this.setData({
					hasReadAgreementDetail: true,
					agreement: true,
				})
				store.hasReadAgreementDetail.set(true)
				store.agreement.set(true)
			}
			const popup = this.selectComponent("#bottom-popup")
			popup.hide()
		},
		//勾选了协议同意
		handleAgreementChange(val) {
			if (
				val &&
				val.currentTarget &&
				val.currentTarget.dataset &&
				val.currentTarget.dataset.trigger
			) {
				//检查用户有无阅读过协议
				if (this.data.hasReadAgreementDetail === false) {
					//打开协议详情弹框
					this.handleOpenAgreementDetail()
					return
				}
				//事件的触发对象
				const trigger = val.currentTarget.dataset.trigger
				switch (trigger) {
					case "checkbox-group":
						if (
							val.detail.value.length > 0 &&
							val.detail.value[0] === "checked"
						) {
							this.setData({
								agreement: true,
							})
						} else {
							this.setData({
								agreement: false,
							})
						}
						break
					case "text":
						const agreement = this.data.agreement
						this.setData({
							agreement: !agreement,
						})
						store.agreement.set(!agreement)
					default:
						break
				}
			}
		},
	},
})
